<?php

namespace App\Http\Controllers\Api\V1\Requests;

use Closure;
use App\Models\User;
use App\Models\Order;
use App\Models\Address;

class ApplyGoldWastesOrderRequest extends FormRequest
{
    protected ?Address $address = null;

    public function rules(): array
    {
        /**
         * @var User $user
         */
        $user = $this->user();

        if ($user->myAllGoldWastesCount() <= 0) {
            fail('无可领取记录');
        }

        $addressId =  (int)request('address');
        if ($addressId) {
            $this->address = Address::find($addressId);
        }

        return [
            'address' => [
                'required',
                'integer',
                'min:1',
                $this->address()
            ],
            'pay_code' => $this->paycode(false)
        ];
    }

    public function attributes(): array
    {
        return ['pay_code' => '交易密码'];
    }

    public function address(): Closure
    {
        return function ($attribute, $value, $fail) {
            if (!$this->address) {
                return $fail('地址不存在');
            } elseif (!Order::isAddressSupported($this->address)) {
                return $fail('地址不在配送范围');
            }
            return true;
        };
    }

    public function getAddress(): Address
    {
        return $this->address;
    }
}
